package com.lyn.advance.fragments;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.lyn.advance.R;
import com.lyn.advance.interfaces.Advance;

import java.util.ArrayList;
import java.util.List;

/**
 * 图片fragment
 * @author longyn 2023/6/30
 * @version 1.0.0
 */
public class PictureFragment extends Fragment implements Advance,Runnable {

    private static final String TAG = "PictureFragment";

    private final Handler handler = new Handler(Looper.getMainLooper());

    //图片url 包括文件路径 网络url
    private String url;

    private final List<AdvanceListener> advanceListenerList = new ArrayList<>();

    //停留时间 单位毫秒
    private long intervalTime = 5000;


    @Override
    public void init(String path) {
        this.url = path;
    }

    @Override
    public void setType(Type type) {

    }

    public void setAdvanceListener(@NonNull AdvanceListener advanceListener) {
        this.advanceListenerList.add(advanceListener);
    }

    @Override
    public void removeAdvanceListener(AdvanceListener advanceListener) {
        for (AdvanceListener next : advanceListenerList) {
            if (next.equals(advanceListener)) {
                advanceListenerList.remove(next);
            }
        }
    }


    @Override
    public void setIntervalTime(long intervalTime) {
        this.intervalTime = intervalTime;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_picture, container, false);
        AppCompatImageView pictureImage = view.findViewById(R.id.picture_image);
        Log.d(TAG,"onCreateView");
        Glide.with(this).load(url).into(pictureImage);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG,"onDestroyView");
        handler.removeCallbacks(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG,"onResume");
        handler.removeCallbacks(this);
        handler.postDelayed(this, intervalTime);
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG,"onPause");
        handler.removeCallbacks(this);
    }

    @Override
    public void run() {
        if (!advanceListenerList.isEmpty()){
            Log.d(TAG,"onCompletion");
            for (AdvanceListener advanceListener:advanceListenerList){
                advanceListener.onCompletion(Type.PICTURE);
            }
        }
    }
}
